package cn.chinaunicom.sdsi.gacx.contractMng.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.chinaunicom.sdsi.gacx.contractMng.entity.TravelContractModelEntity;
import cn.chinaunicom.sdsi.gacx.contractMng.service.ContractMngService;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("contractMngController")
public class ContractMngController {
	
	@Value("${UPLOAD_CONTRACT_PATH}")//公安案件上传地址
    private String path;

	@Autowired
	private ContractMngService contractMngService;
	
	@RequestMapping("toContractMngJsp")
	public ModelAndView toContractMngJsp(ModelAndView mv, String type, HttpServletRequest request){
		request.setAttribute("menuType", type);
		mv.setViewName("gacx/contractmng/contractmng");
		return mv;
	}
	
	@RequestMapping("qryTrlContMdlList")
	public void qryTrlContMdlList(String contractName, Integer start, Integer length, HttpServletResponse response) throws Exception{
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(contractMngService.qryTrlContMdlList(contractName, start, length).toString());
	}
	
	@RequestMapping("/uploadContractTmp")
    @ResponseBody
	public JSONObject uploadContractTmp(TravelContractModelEntity tcme) throws Exception{
		JSONObject obj = new JSONObject();
		if(contractMngService.qryTrlContMdlByName(tcme.getContractName()) >0){
			obj.put("msg", "该模板名称已经存在！");
            obj.put("res", "error");
            return obj;
		}
		
        MultipartFile myfile = tcme.getMyfile();
        long length = myfile.getSize();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String myFileName = "";//原文件名
        String fileName = "";//新文件名
        boolean flag = false;
        if (myfile != null) {
            //取得当前上传文件的文件名称  
            myFileName = myfile.getOriginalFilename();
            String end = this.getExtend(myFileName);
            //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
            if (myFileName.trim() != "") {
                String in_date = df.format(new Date()).replaceAll(" ", "").replaceAll(":", "");//获取当前时间
                //重命名上传后的文件名  
                fileName = "TrvlTmp" + in_date + "." + end;  //重命名格式：GaAj+当前时间+随机数
                tcme.setFile(fileName);
                //生成ID
                String contractId = "LYHT" + df.format(new Date()) + ((int) (Math.random() * 900) + 100);// new Date()为获取当前系统时间
                tcme.setContractId(contractId);
                //定义上传路径 
                String uploadpath = "";
                if (path.indexOf(".") != -1) {
                    uploadpath = path;
                } else {
                    uploadpath = path + fileName;
                }
                try {
                    File localFile = new File(uploadpath);
                    myfile.transferTo(localFile);
                    flag = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (flag) {
            // 新增
        	contractMngService.saveContractTmp(tcme);
            obj.put("msg", "合同模板上传成功!");
            obj.put("res", "success");
        } else {
            obj.put("res", "error");
            obj.put("msg", "文件为空！");
        }
        obj.put("oldname", myFileName);
        obj.put("path", false);
        obj.put("size", (length / 1024));
        obj.put("length", length);
        return obj;
	}
	
	/**
     * 下载案件证明
     *
     * @param dzghApplyEntity
     * @return
     */
    @RequestMapping("/downloadContractTmp")
    @ResponseBody
    public void downloadContractTmp(String contractId, HttpServletRequest request, HttpServletResponse response) {
    	TravelContractModelEntity bean = contractMngService.qryTrvlTmpMdlById(contractId);
        String newFileName = bean.getFile();

        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        //获取下载文件路径
        String downLoadPath = "";
        if (path.indexOf(".") != -1) {
            downLoadPath = path;
        } else {
            downLoadPath = path + newFileName;
        }

        //获取文件的长度
        long fileLength = new File(downLoadPath).length();

        //获取文件
        File file = new File(downLoadPath);

        //判断是否为图片格式
        if (this.isImage(file)) {
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            try {
                response.setHeader("Content-disposition",
                        "attachment; filename=" + new String(newFileName.getBytes("utf-8"), "ISO8859-1"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            // 设置文件输出类型
            response.setContentType("application/octet-stream");
            try {
                response.setHeader("Content-disposition",
                        "attachment; filename=" + new String(newFileName.getBytes("utf-8"), "ISO8859-1"));
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            // 设置输出长度
            response.setHeader("Content-Length", String.valueOf(fileLength));
        }
        //获取输入流
        try {
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //输出流
        try {
            bos = new BufferedOutputStream(response.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] buff = new byte[2048];
        int bytesRead;
        try {
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //关闭流
        try {
            bis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            bos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    
    @RequestMapping("/delContractTmp")
    @ResponseBody
    public boolean delContractTmp(String contractId){
    	int i = this.contractMngService.delTrlContMdlById(contractId);
        if (i >= 0)
            return true;
        else
            return false;
    	
    }
	
	/**
     * 获取文件扩展名
     *
     * @param filename
     * @return
     */
    public static String getExtend(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');

            if ((i > 0) && (i < (filename.length() - 1))) {
                return (filename.substring(i + 1)).toLowerCase();
            }
        }
        return null;
    }
    
    /**
     * 判断是否为图片
     *
     * @param file
     * @return
     */
    public static boolean isImage(File file) {
        if (file.isDirectory()) {
            return false;
        }
        String fileName = file.getName();
        int len = fileName.indexOf(".");
        String imagesPattern = fileName.substring(len + 1, fileName.length()).toLowerCase();
        if ("jpg".equals(imagesPattern)) {
            return true;
        } else if ("bmp".equals(imagesPattern)) {
            return true;
        } else if ("gif".equals(imagesPattern)) {
            return true;
        } else if ("psd".equals(imagesPattern)) {
            return true;
        } else if ("pcx".equals(imagesPattern)) {
            return true;
        } else if ("png".equals(imagesPattern)) {
            return true;
        } else if ("dxf".equals(imagesPattern)) {
            return true;
        } else if ("cdr".equals(imagesPattern)) {
            return true;
        } else if ("ico".equals(imagesPattern)) {
            return true;
        } else if ("bmp".equals(imagesPattern)) {
            return true;
        } else if ("jpeg".equals(imagesPattern)) {
            return true;
        } else if ("svg".equals(imagesPattern)) {
            return true;
        } else if ("wmf".equals(imagesPattern)) {
            return true;
        } else if ("emf".equals(imagesPattern)) {
            return true;
        } else if ("eps".equals(imagesPattern)) {
            return true;
        } else if ("tga".equals(imagesPattern)) {
            return true;
        } else if ("nef".equals(imagesPattern)) {
            return true;
        } else if ("tif".equals(imagesPattern)) {
            return true;
        } else if ("tiff".equals(imagesPattern)) {
            return true;
        } else {
            return false;
        }

    }
}
